<template>
  <div class="forgot-password-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="忘记密码"
      class="forgot-password-header"
      left-text="返回"
      left-arrow
      @click-left="handleBack"
      :border="false"
    />

    <!-- 找回密码表单区域 -->
    <div class="forgot-password-form-wrapper">
      <!-- 表单Logo -->
      <div class="logo-container">
        <van-image
          src="/logo.png"
          alt="Logo"
          class="logo"
        />
        <p class="app-name">小鸡目录</p>
      </div>

      <!-- 找回密码表单 - 使用标准van-form格式 -->
      <van-form ref="forgotFormRef" class="forgot-password-form">
        <!-- 邮箱输入框 -->
        <van-field
          v-model="email"
          name="email"
          placeholder="请输入注册邮箱"
          :rules="[
            { required: true, message: '请输入邮箱' }, 
            { pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, message: '请输入正确的邮箱格式' }
          ]"
          class="form-item"
        >
          <template #left-icon>
            <van-icon name="mail-o" class="input-icon" />
          </template>
        </van-field>

        <!-- 验证码输入框 -->
        <van-field
          v-model="verificationCode"
          name="verificationCode"
          placeholder="请输入验证码"
          :rules="[{ required: true, message: '请输入验证码' }]"
          class="form-item"
        >
          <template #left-icon>
            <van-icon name="captcha" class="input-icon" />
          </template>
          <template #button>
            <van-button
              :disabled="sendingCode || countdown > 0"
              size="small"
              type="default"
              class="send-code-button"
              @click="sendVerificationCode"
            >
              {{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
            </van-button>
          </template>
        </van-field>

        <!-- 新密码输入框 -->
        <van-field
          v-model="newPassword"
          type="password"
          name="newPassword"
          placeholder="请输入新密码"
          :rules="[
            { required: true, message: '请输入新密码' }, 
            { min: 6, message: '密码长度不能少于6位' }
          ]"
          class="form-item"
          :show-password="showNewPassword"
        >
          <template #left-icon>
            <van-icon name="lock" class="input-icon" />
          </template>
          <template #right-icon>
            <van-icon 
              :name="showNewPassword ? 'eye-o' : 'closed-eye'"
              class="input-icon"
              @click="toggleNewPasswordVisibility"
            />
          </template>
        </van-field>

        <!-- 重置密码按钮 -->
        <van-button
          type="primary"
          class="reset-password-button"
          @click="handleResetPassword"
          :loading="submitting"
          native-type="submit"
        >
          重置密码
        </van-button>

        <!-- 登录链接 -->
        <div class="login-link">
          记得密码了? <router-link to="/login">返回登录</router-link>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from "@/utils/axios.js";
import { showToast } from 'vant';
import 'vant/lib/toast/style';
const router = useRouter();
const forgotFormRef = ref(null);

// 表单数据
const email = ref('');
const verificationCode = ref('');
const newPassword = ref('');
const showNewPassword = ref(false);
const countdown = ref(0);
const sendingCode = ref(false);
const submitting = ref(false);

// 返回上一页
const handleBack = () => {
  router.back();
};

// 切换密码可见性
const toggleNewPasswordVisibility = () => {
  showNewPassword.value = !showNewPassword.value;
};

// 发送验证码
const sendVerificationCode = async () => {
  // 先验证邮箱格式是否正确
  if (!/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(email.value)) {
    showToast('请输入正确的邮箱格式');
    return;
  }

  sendingCode.value = true;
  try {
    const url = "/api/sendCode/"+email.value;
    await axios.get(url, {
      email: email.value
    });
    showToast('验证码发送成功');
    
    // 开始倒计时
    startCountdown();
  } catch (error) {
    console.log('发送验证码失败', error);
    showToast('发送验证码失败，请稍后重试');
  } finally {
    sendingCode.value = false;
  }
};

// 倒计时功能
const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// 重置密码
const handleResetPassword =  () => {
  axios.get("/api/verify/"+email.value+"/"+verificationCode.value)
      .then( res => {
          if (res.code == 200) {
              submitting.value = true;
              try {
                  const url = "/api/users/resetPwd?email="+email.value+"&pwd="+newPassword.value;
                   axios.post(url)
                       .then(res=>{
                      if (res.code==200){
                          showToast('密码重置成功');
                          // 重置成功后跳转到登录页面
                          setTimeout(() => {
                              router.push('/login');
                          }, 1500);
                      }
                   })
              } catch (error) {
                  showToast('重置密码失败，请稍后重试');
              } finally {
                  submitting.value = false;
              }
          }else {
              showToast('验证码错误，请稍后重试');
          }
      })

};
</script>

<style lang="less" scoped>
.forgot-password-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.forgot-password-header {
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.forgot-password-form-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 40px 24px 24px;
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40px;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 16px;
}

.app-name {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.forgot-password-form {
  background-color: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.form-item {
  margin-bottom: 20px;
}

.input-icon {
  color: #999;
}

.send-code-button {
  font-size: 13px;
  padding: 0;
  width: auto;
  color: #1989fa;
}

.reset-password-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  border-radius: 24px;
  margin-bottom: 20px;
}

.login-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.login-link a {
  color: #1989fa;
  text-decoration: none;
}
</style>